package com.talkweb.historylib.provider;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.RecycleItemProvider;
import ohos.app.AbilityContext;

import java.util.ArrayList;
import java.util.List;

/**
 * @author SUQI
 * @date 2021/1/28
 * @description 列表公共适配器
 **/
public abstract class BaseListProvider<T> extends RecycleItemProvider {

    private Ability mContext;
    private List<T> mDatas;

    public BaseListProvider(Ability mContext) {
        this.mContext = mContext;
        mDatas = new ArrayList<>();
    }

    @Override
    public int getCount() {
        return mDatas == null || mDatas.isEmpty() ? 0 : mDatas.size();
    }

    @Override
    public T getItem(int i) {
        return i > 0 && i < mDatas.size() ? mDatas.get(i) : null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        ViewHolder viewHolder = ViewHolder.createViewHolder(mContext, componentContainer, getLayoutId());
        onBindViewHolder(viewHolder, mDatas.get(i), i);
        return viewHolder.getConvertComponent();
    }

    /**
     * 初始化item，并设置item数据
     *
     * @param viewHolder
     * @param data
     * @param position
     */
    protected abstract void onBindViewHolder(ViewHolder viewHolder, T data, int position);

    /**
     * 获取item资源id
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 设置列表数据源
     * @param list
     */
    public void setDataList(List<T> list) {
        if (list != null) {
            mDatas.clear();
            mDatas.addAll(list);
            notifyDataChanged();
        }
    }

    /**
     * 获取上下文
     * @return
     */
    public Ability getAbilityContext() {
        return mContext;
    }

    /**
     * 获取数据
     * @return
     */
    public List<T> getDataList() {
        return mDatas;
    }
}
